from ma.commons.core.abstractmapper import AbstractMapper
import re

no_of_keys = 20


class Map(AbstractMapper):
    """this is the user defined map function 
    """
    
    def  __init__(self, filename, filecontents, key_value_dict):    
        """
        """
        
        AbstractMapper.__init__(self, filename, filecontents, key_value_dict)
        
        self.list_of_keys = Map.generate_keys()
        #self.generate_keys()
        print("Map size list of keys:", len(self.list_of_keys))    
    
    
    def map(self, filename, filecontents):
        """the user map function
        """
        
        # bisect word through alphanumeric chars
        #list_of_words = re.findall(r'\w+',filecontents)
        
        # bisect words on whitespace characters
        list_of_words = re.findall(r'\S+',filecontents)
        
        for word in list_of_words:    
            if word in self.list_of_keys:
                self.emit(word,[1])
    
    
    @staticmethod            
    def get_cycled_word(i, no_letters):
        word = ''
        for j in range(no_letters):
            word += 'a'
        pos = 0
        while i > 0:
            letter = chr(ord('a') + (i % 26))
            i = i / 26
            prv_word = ''
            if pos != 0:
                prv_word = word[-pos:]
            word = word[:-1-pos] + letter + prv_word
            pos += 1
            if pos >= no_letters:
                raise
        return word
    
    
    @staticmethod
    def generate_keys():
        k = []
        for idx in range(no_of_keys):
            word = Map.get_cycled_word(idx, 6)
            k.append(word + '.' + word + '.' + word)
        return k
    
    